package org.jsping.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsping.entity.Music;
import org.jsping.music.NewMusic;
import org.jsping.service.impl.MusicServiceImpl;

/**
 * 用户搜索出来的数据进行超链接点击之后,把歌曲名和歌手名传回来,然后以此来判断进行要不要添加数据
 * 如果添加成功的话会返回mid回去,最后用户根据这个mid再发送请求跳转至playListen页面去判断musicplay页面是否有打开
 * 打开的话则把mid传回去,没有则直接播放这首歌
 */
@WebServlet("/MusicAdd")
public class MusicAdd extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public MusicAdd() {
        super();
    }

    MusicServiceImpl msi = new MusicServiceImpl();
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String mname = request.getParameter("mname");  
		String sname = request.getParameter("sname");
		int mid = msi.isExists(mname, sname);
		//如果不存在这个mid
		if( mid <= 0 ) {
			try {
				/*就执行插入的语句*/
				String purl = request.getParameter("purl");
				String murl = request.getParameter("murl").replaceAll("abc123", "&");
				String mymid = request.getParameter("mymid");
				String lyric = NewMusic.getlyric(mymid);  //根据对应的mid来得到歌词
				Music music = new Music();
				music.setLyric(lyric);
				music.setMname(mname);
				music.setMurl(murl);
				music.setPurl(purl);
				music.setSname(sname);
				//添加成功,获取到对应的id
				if(msi.addMusic(music)) {
					mid = msi.isExists(mname, sname);
					System.out.println("此时的mid为:"+mid);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		PrintWriter out = response.getWriter();
		out.print(mid);
		out.flush();
		out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
